<template>
  <view class="post-container">
    <view class="form-box">
      <input 
        v-model="form.title" 
        placeholder="例如: XX乡村学校急需数学老师" 
        class="input-item"
      />
      <input 
        v-model="form.schoolName" 
        placeholder="请输入学校全名" 
        class="input-item"
      />
      <view class="subject-picker">
        <picker 
          mode="selector" 
          :range="subjects" 
          @change="handleSubjectChange"
          class="picker"
        >
          <view class="picker-content">
            <text class="placeholder" v-if="!form.subject">请选择所需支教科目</text>
            <text v-else>{{ form.subject }}</text>
          </view>
        </picker>
      </view>
      <textarea 
        v-model="form.content" 
        placeholder="请描述您的学校具体需求、现状等信息" 
        class="textarea-item"
      />
      <view class="image-uploader">
        <view class="title">添加图片(选填)</view>
        <view class="image-list">
          <view 
            class="image-item" 
            v-for="(img, index) in form.images" 
            :key="index"
          >
            <image 
              :src="img.includes('data:image') ? img : img.startsWith('http') ? img : '/storage' + img" 
              mode="aspectFill" 
            />
            <text class="delete-btn" @click="deleteImage(index)">×</text>
          </view>
          <view 
            class="upload-btn" 
            @click="chooseImage" 
            v-if="form.images.length < 3"
          >
            <text class="icon">+</text>
            <text class="tip">最多3张</text>
          </view>
        </view>
      </view>
      <button 
        class="submit-btn" 
        :disabled="!isValid"
        @click="handleSubmit"
      >
        发布需求
      </button>
      
      <view class="why-important">
        <view class="title">为什么支教很重要?</view>
        <text class="content">支教能够为乡村学校带来宝贵的教育资源，帮助缩小城乡教育差距。通过支教，我们可以为乡村孩子们提供更多的学习机会和更广阔的视野，同时也能促进教育公平，推动乡村教育的发展。您的参与将为乡村教育带来积极的改变!</text>
      </view>
    </view>
  </view>
</template>

<script>
import apiConfig from '@/utils/config.js'
import { getSystemInfo } from '@/utils/system.js'

export default {
  data() {
    return {
      form: {
        title: '',
        schoolName: '',
        subject: '',
        content: '',
        images: []
      },
      subjects: ['语文', '数学', '英语', '物理', '化学', '生物', '历史', '地理', '音乐', '美术', '体育'],
      apiConfig,
      statusBarHeight: 44 // 默认值
    }
  },
  computed: {
    isValid() {
      return this.form.title && 
             this.form.schoolName && 
             this.form.subject && 
             this.form.content
    }
  },
  methods: {
    handleSubjectChange(e) {
      this.form.subject = this.subjects[e.detail.value]
    },
    chooseImage() {
      uni.chooseImage({
        count: 3 - this.form.images.length,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          this.form.images = [...this.form.images, ...res.tempFilePaths]
        }
      })
    },
    deleteImage(index) {
      this.form.images.splice(index, 1)
    },
    async handleSubmit() {
      if (!uni.getStorageSync('userInfo')) {
        uni.showToast({ title: '请先登录', icon: 'none' })
        setTimeout(() => uni.navigateTo({ url: '/pages/login/index' }), 1500)
        return
      }
      
      let loadingShown = false
      try {
        const showLoading = () => {
          if (!loadingShown) {
            uni.showLoading({ title: '发布中...', mask: true })
            loadingShown = true
          }
        }
        
        showLoading()
        const uploadedImages = []
        
        if(this.form.images.length > 0) {
          const uploadPromises = this.form.images.map(img => {
            return this.uploadImage(img)
              .then(res => res.url)
              .catch(e => {
                console.error('图片上传失败:', e)
                uni.showToast({
                  title: `上传失败: ${e.message || '网络错误'}`,
                  icon: 'none'
                })
                return null
              })
          })
          
          const results = await Promise.all(uploadPromises)
          uploadedImages.push(...results.filter(url => url !== null))
          
          if(results.some(url => url === null)) {
            uni.showToast({ title: '部分图片上传失败', icon: 'none' })
          }
        }
        
        try {
          const newPost = {
            id: Date.now(),
            author: {
              name: uni.getStorageSync('userInfo')?.nickname || '匿名用户',
              avatar: uni.getStorageSync('userInfo')?.avatarUrl || '/static/avatar-default.png'
            },
            content: this.form.content,
            createTime: new Date().toISOString(),
            subject: this.form.subject,
            images: uploadedImages,
            likes: 0,
            comments: 0,
            location: this.form.location
          }

          const posts = uni.getStorageSync('posts') || []
          posts.unshift(newPost)
          uni.setStorageSync('posts', posts)
        } catch (storageError) {
          throw new Error('本地存储失败，请检查存储空间')
        }

        uni.showToast({ title: '发布成功', icon: 'success' })
        
        setTimeout(() => {
          const pages = getCurrentPages()
          if (pages.length > 1) {
            uni.navigateBack()
          } else {
            uni.switchTab({ url: '/pages/index/index' })
          }
        }, 1500)
        
      } catch(e) {
        uni.showToast({
          title: '发布失败：' + (e.message || '未知错误'),
          icon: 'none',
          duration: 3000
        })
      } finally {
        if(loadingShown) {
          uni.hideLoading()
        }
      }
    },
    uploadImage(tempFilePath) {
      return new Promise((resolve, reject) => {
        const savePath = `${wx.env.USER_DATA_PATH}/${Date.now()}.jpg`
        const fileManager = uni.getFileSystemManager()
        
        fileManager.saveFile({
          tempFilePath,
          filePath: savePath,
          success: () => resolve({ url: savePath }),
          fail: () => reject(new Error('图片保存失败'))
        })
      })
    },
    onLoad() {
      const { statusBarHeight } = getSystemInfo()
      this.statusBarHeight = statusBarHeight || 44 // 默认值
    },
    async getLocation() {
      try {
        const setting = await uni.getSetting({})
        if (!setting.authSetting['scope.userLocation']) {
          await uni.authorize({
            scope: 'scope.userLocation'
          })
        }
        
        const res = await uni.getLocation({
          type: 'gcj02',
          isHighAccuracy: true
        })
        this.form.location = {
          latitude: res.latitude,
          longitude: res.longitude
        }
      } catch (e) {
        console.error('获取位置失败:', e)
        uni.showToast({
          title: '需要位置权限以标记学校位置',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.post-container {
  padding: 60rpx;
  
  .form-box {
    background: #fff;
    border-radius: 20rpx;
    padding: 40rpx;
    
    .input-item {
      height: 80rpx;
      border-bottom: 1rpx solid #eee;
      margin-bottom: 30rpx;
      padding: 0 20rpx;
    }
    
    .subject-picker {
      border-bottom: 1rpx solid #eee;
      margin-bottom: 30rpx;
      
      .picker {
        height: 80rpx;
        
        .picker-content {
          height: 80rpx;
          line-height: 80rpx;
          padding: 0 20rpx;
          
          .placeholder {
            color: #999;
          }
        }
      }
    }
    
    .textarea-item {
      width: 100%;
      height: 300rpx;
      border: 1rpx solid #eee;
      border-radius: 12rpx;
      padding: 20rpx;
      margin-bottom: 30rpx;
      font-size: 28rpx;
    }
    
    .image-uploader {
      margin: 30rpx 0;
      
      .title {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 20rpx;
      }
      
      .image-list {
        display: flex;
        flex-wrap: wrap;
        gap: 20rpx;
        
        .image-item {
          position: relative;
          width: 180rpx;
          height: 180rpx;
          
          image {
            width: 100%;
            height: 100%;
            border-radius: 12rpx;
          }
          
          .delete-btn {
            position: absolute;
            top: -20rpx;
            right: -20rpx;
            width: 40rpx;
            height: 40rpx;
            line-height: 40rpx;
            text-align: center;
            background: rgba(0,0,0,0.5);
            color: #fff;
            border-radius: 50%;
            font-size: 32rpx;
          }
        }
        
        .upload-btn {
          width: 180rpx;
          height: 180rpx;
          border: 2rpx dashed #ddd;
          border-radius: 12rpx;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          
          .icon {
            font-size: 60rpx;
            color: #999;
            margin-bottom: 10rpx;
          }
          
          .tip {
            font-size: 24rpx;
            color: #999;
          }
        }
      }
    }
    
    .submit-btn {
      margin-top: 50rpx;
      background: rgba(91, 192, 235, 0.8);
      color: #fff;
      border-radius: 40rpx;
      
      &[disabled] {
        background: #ccc;
      }
    }
    
    .why-important {
      margin-top: 60rpx;
      padding-top: 30rpx;
      border-top: 1rpx solid #eee;
      text-align: center;
      
      .title {
        font-size: 28rpx;
        color: #5bc0eb;
        font-weight: bold;
        margin-bottom: 20rpx;
      }
      
      .content {
        font-size: 24rpx;
        color: #5bc0eb;
        line-height: 1.6;
        opacity: 0.8;
      }
    }
  }
}
</style> 